package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;

import model.Behandling;
import model.Lager;
import model.LagerPlads;
import model.ProduktType;
import model.Statistik;

/**
 * 
 * @author Lars
 *
 */

public class DaoJPA {
	private static DaoJPA dao;
	
	private static EntityManagerFactory emf;
	private static EntityManager em;
	private static EntityTransaction tx;
	
	public static DaoJPA getInstance(){
		if(dao == null)
			dao = new DaoJPA();
		
		return dao;
	}
	
	private DaoJPA(){
		emf = Persistence.createEntityManagerFactory("carletti");
		em = emf.createEntityManager();
		tx = em.getTransaction();
	}
	
	public void storeBehandling(Behandling behandling) {
		tx.begin();
		em.persist(behandling);
		tx.commit();
	}
	
	public void updateBehandling(Behandling behandling) {
		tx.begin();
		Behandling b = em.find(Behandling.class, behandling.getID());
		b = behandling;
		tx.commit();
	}
	
	public void removeBehandling(Behandling behandling) {
		tx.begin();
		
		em.remove(behandling);
		
		tx.commit();
	}
	
	public List<Behandling> getBehandlinger() {
		return em.createQuery("SELECT b FROM Behandling b", Behandling.class).getResultList();
	}
	
	public List<ProduktType> getProduktTyper(){
		return em.createQuery("SELECT p FROM ProduktType p", ProduktType.class).getResultList();
	}
	
	public void setLager(Lager lager){
		tx.begin();
		em.persist(lager);
		tx.commit();
	}
	
	public Lager getLager() {
		try {
			return em.createQuery("SELECT L FROM Lager L", Lager.class).getSingleResult();
		}
		catch(NoResultException ex) {
			return null;
		}
	}
	
	public void storeLagerPlads(LagerPlads lagerPlads) {
		tx.begin();
		em.persist(lagerPlads);
		tx.commit();
	}
	
	public void storeProduktType(ProduktType produktType){
		tx.begin();
		em.persist(produktType);
		tx.commit();
	}
	
	public void removeProduktType(ProduktType produktType) {
		tx.begin();
		em.remove(produktType);
		tx.commit();
	}
	
	public void setStatistik(Statistik statistik) {
		tx.begin();
		em.persist(statistik);
		tx.commit();
	}
	
	public Statistik getStatistik() {
		try {
			return em.createQuery("SELECT S FROM Statistik S", Statistik.class).getSingleResult();
		}
		catch(NoResultException ex) {
			return null;
		}
	}
}
